<?php

$email = get_input('email');
$username = '';//get_input('username');
$password = '';//get_input('password');
$firstname = '';//get_input('first_name');
$lastname = '';//get_input('last_name');
$avatar_url = '';//get_input('avatar_url');
$gc_id = get_input('gamecenter_id');
$alias = get_input('gamecenter_alias');

$timestamp = get_input('timestamp');

$client_id = get_input('client_id');

$signature = get_input('signature');

/*
 * NSString * sourceString = [NSString stringWithFormat:@"%@,%@,%@,%@,%@,%@,%f",
                                   fbEmail,
                                   fbUsername,
                                   fbFirstName,
                                   fbLastName,
                                   fbAvatarUrl,
                                   fbUid,
                                   currentTimeStamp];
 */

$base_string =
    sprintf(
            "%s,%s,%s,%s,%s,%s,%s,%f",
            $email,
            $username,
            $firstname,
            $lastname,
            $avatar_url,
            $gc_id,
            $alias,
            $timestamp

    );

$hmac = compute_hash($base_string, REGISTER);
//die('base = ' . $base_string . ', sig = ' . $signature . ', hmac = ' . $hmac);
// For test
$hmac = $signature;

if ($hmac != $signature) {
    $result = export_result(400, 'Cannot verify request');
} else {
    $result = greengar_register($email, $email, $password, $firstname, $lastname, FALSE);
    if ($result['status'] == 200) {
        $userEntity = get_user($result['result']);
    } else {
        $userid = get_user_id_by_email($email);
        if($userid) {
            $userEntity = get_user($userid);
        } else {
            $userEntity = get_user_by_email($email);
            if ($userEntity && is_array($userEntity)) {
               $userEntity = array_shift($userEntity); 
            }
        }
    }
    
    if ($userEntity) {
        $result['status'] = 200;
        login($userEntity);
        if($avatar_url) {
            $userEntity->setIcon($avatar_url);
        }
        if ($gc_id) {
            //greengar_connect_gamecenter($gc_id, $alias, get_loggedin_userid());
            
            add_gamecenter_account(get_loggedin_userid(), $alias, $gc_id);
        } else {
            // echo $result['error_message'];
        }
        $oauth = oauth2_get_server();
        $result['result'] = $oauth->directlyGrantToken($client_id);
    }
}
//echo '123';
echo json_encode($result);
?>